import time

import allure
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.webdriver import WebDriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.wait import WebDriverWait

from util.log_util import logger


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if driver is None:
            # 初始化
            service = Service(executable_path=ChromeDriverManager().install())
            self.driver = webdriver.Chrome(service=service)
            # 窗口最大化
            self.driver.maximize_window()
        else:
            self.driver = driver

    """
    打开页面
    """
    def url(self, url):
        self.driver.get(url)

    """
    查找元素
    """
    def find_ele(self, by, value=None):
        try:
            if value is None:
                res = self.driver.find_element(*by)
            else:
                res = self.driver.find_element(by=by, value=value)
        except Exception as e:
            res = None
            logger.info(f'未找到元素{by}|{value}')

        return res

    """
    等待，默认等待8秒
    """
    def wait(self, method, time=8):
        res = WebDriverWait(self.driver, time).until(method)
        return res

    """
    关闭窗口
    """
    def quit(self):
        self.driver.quit()

    """
    获取源码
    """
    def get_source(self):
        source = time.strftime('%Y%m%d%H%M%S')
        with open(f'../PageSource/{source}.yaml', 'w') as f:
            f.write(self.driver.page_source)

    """
    截图
    """
    def screenshot(self):
        screen = time.strftime('%Y%m%d%H%M%S')
        self.driver.save_screenshot(f'../screenshot/{screen}.png')
        allure.attach.file(f'../screenshot/{screen}.png',
                           name=screen,
                           attachment_type=allure.attachment_type.PNG,
                           extension='png')

